var plgnins = require('gulp-load-plugins')();
var gulp = require('gulp');
var gulpSequence = require('gulp-sequence');
var autoprefixer = require('autoprefixer');
var bs = require('browser-sync').create();
var fs = require('fs');
var yaml = require('js-yaml');
var del = require('del');
var util = require('util');
var urlParse = require('url').parse;

gulp.task('default',gulpSequence('clean', 'main_module', 'app_img', 'app_css', 'module_css', 'app_js', 'module_js', 'template_js', 'index_html', 'watch'));

gulp.task('testing',gulpSequence('clean', 'main_module', 'app_img', 'app_css', 'module_css', 'app_js', 'module_js', 'template_js', 'index_html'));

gulp.task('product',gulpSequence('clean', 'main_module', 'app_img', 'app_css', 'module_css', 'app_js', 'module_js', 'template_js', 'index_html'));

var config = loadConfig();

function loadConfig() {
    var env = 'default';
    var config;
    var configStr = fs.readFileSync('./app.yaml','utf-8');
    if(process.argv.indexOf('-e')>-1){
        env = process.argv[process.argv.indexOf('-e')+1].trim();
    }
    config = yaml.safeLoad(configStr, 'utf-8');
    configStr = configStr.replace(/\{source\}/img, config[env]['source'])
        .replace(/\{target\}/img, config[env]['target']);
    config = yaml.safeLoad(configStr, 'utf-8');
    config = config[env];
    console.log(config['clean']);
    return config;
}

gulp.task('main_module', function () {
    var stream = gulp.src(config.build.main_module)
        .pipe(gulp.dest(config.target + '/resource/js'));
    return stream;
})

gulp.task('index_html', function () {
    var stream = gulp.src(config.build.index_html)
        .pipe(gulp.dest(config.target));
    return stream;
})

gulp.task('clean', function () {
    return gulp.src(config.clean)
        .pipe(plgnins.plumber())
        .pipe(plgnins.clean({force: true}));
})

gulp.task('app_js', function () {
    var globalWrap = config.prependJs + '\nwindow.vs_env = window.ENV = \n' + util.inspect(config.vs_env) + ';\n' +
        'window.appModule = angular.module("App", window.vs_env.MODULES);\n<%= contents %>\n' + config.appendJs;
    var stream = gulp.src(config.build.app_js)
        .pipe(plgnins.plumber())
        .pipe(plgnins.naturalSort())
        .pipe(plgnins.wrap('(function(angular,window,document){\n<%= contents %>\n})(angular,window,document);'))
        .pipe(plgnins.concat('app.js'))
        .pipe(plgnins.wrap(globalWrap))
        .pipe(plgnins.ngAnnotate()) //依赖注入
        .pipe(plgnins.if(config.min,plgnins.uglify()))
        .pipe(gulp.dest(config.target + '/app/js'));

    if(config.rev){
        stream = rev(stream,'js');
    }

    if(bs.active){
        setTimeout(function () {
            bs.reload();
        },200);
    }
    return stream;
})

gulp.task('module_js',function () {
    var stream = gulp.src(config.build.lib_js)
        .pipe(plgnins.plumber())
        //    .pipe(plgnins.naturalSort())
        .pipe(plgnins.concat('lib.js'))
        .pipe(plgnins.if(config.min,plgnins.uglify()))
        .pipe(gulp.dest(config.target + '/app/js'));

    if(config.rev){
        stream = rev(stream,'js');
    }

    if(bs.active){
        setTimeout(function () {
            bs.reload();
        },200);
    }
    return stream;
})

gulp.task('app_img',function(){
    var stream = gulp.src(config.build.app_img)
        //.pipe(plgnins.cache(plgnins.imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
        .pipe(gulp.dest(config.target+'/resource/images'));

    if(config.rev){
        stream = rev(stream,'js');
    }
    return stream;
});

gulp.task('app_css',function(){
    var stream = gulp.src(config.build.app_css)
        .pipe(plgnins.plumber())
        .pipe(plgnins.naturalSort())
        //.pipe(plgnins.sassBulkImport())
        //.pipe(plgnins.sass({outputStyle: 'expanded'}).on('error', plgnins.sass.logError))
        //.pipe(plgnins.postcss([autoprefixer({browsers: ['last 5 version','ie >= 9']})]))
        .pipe(plgnins.concat('app.css'))
        .pipe(plgnins.if(config.min,plgnins.minifyCss({})))
        .pipe(gulp.dest(config.target + '/resource/css'))
        .pipe(plgnins.if(bs.active,bs.stream()));

    if(config.rev){
        stream = rev(stream,'js');
    }
    return stream;
});

//项目依赖的第三方样式库
gulp.task('module_css',function(){
    var stream = gulp.src(config.build.lib_css)
        .pipe(plgnins.plumber())
        //    .pipe(plgnins.naturalSort())
        .pipe(plgnins.sassBulkImport())
        .pipe(plgnins.sass({outputStyle: 'expanded'}).on('error', plgnins.sass.logError))
        .pipe(plgnins.postcss([autoprefixer({browsers: ['last 5 version','ie >= 9']})]))
        .pipe(plgnins.concat('module.css'))
        .pipe(plgnins.if(config.min,plgnins.minifyCss({})))
        .pipe(gulp.dest(config.target + '/resource/css'))
        .pipe(plgnins.if(bs.active,bs.stream()));

    if(config.rev){
        stream = rev(stream,'js');
    }
    return stream;
});

//包含所有的html代码
gulp.task('template_js',function(){
    var stream = gulp.src(config.build.template_js)
        .pipe(plgnins.plumber())
        .pipe(plgnins.naturalSort())
        .pipe(plgnins.angularTemplatecache('pages.js',{
            standalone: true,
            transformUrl: function(url) {
                return url.replace(/\.html$/, '')
            }
        }))
        .pipe(plgnins.concat('pages.js'))
        .pipe(gulp.dest(config.target + '/app/js'));

    if(config.rev){
        stream = rev(stream,'js');
    }

    if(bs.active){
        setTimeout(function () {
            bs.reload();
        },200);
    }
    return stream;
});

gulp.task('watch',function(){
    gulp.watch(config.build.app_css_watch,['app_css']);
    gulp.watch(config.build.lib_css_watch,['lib_css']);
    gulp.watch(config.build.app_js,['app_js']);
    gulp.watch(config.build.lib_js,['lib_js']);
    gulp.watch(config.build.template_js,['template_js']);

    gulp.watch(config.build.index_html,['index_html']);

    //代码变化后，浏览器自动刷新页面
    /*var proxyUrlConfig = urlParse(config.browserSyncProxy.url);
    merge(config.browserSyncProxy,proxyUrlConfig);
    config.vs_env.APIURL && (config.browserSyncProxy.route = config.vs_env.APIURL);
    config.browserSync.server.middleware = [proxy(config.browserSyncProxy)];*/
    bs.init(config.browserSync);
});

gulp.task('server', function () {
    bs.init(config.browserSync);
})